package com.haiya.infrastructure.db.repository;

import com.haiya.domain.aggregate.cargo.Cargo;
import com.haiya.domain.aggregate.cargo.CargoRepository;
import com.haiya.domain.aggregate.cargo.valueobject.EnterpriseSegment;
import com.haiya.infrastructure.db.converter.CargoConverter;
import com.haiya.infrastructure.db.dataobject.CargoDO;
import com.haiya.infrastructure.db.mapper.CargoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 货物仓库实现
 * @author qiaoguoqiang
 */
@Component
public class CargoRepositoryImpl implements CargoRepository {
    @Autowired
    private CargoMapper cargoMapper;

    @Override
    public Cargo find(String id) {
        CargoDO cargoDO = cargoMapper.selectById(id);
        Cargo cargo = CargoConverter.deserialize(cargoDO);
        return cargo;
    }

    @Override
    public int sizeByCustomer(String customerPhone) {
        return cargoMapper.countByCustomer(customerPhone);
    }

    /**
     * 返回模拟数量
     * @param enterpriseSegment
     * @return
     */
    @Override
    public int sizeByEnterpriseSegment(EnterpriseSegment enterpriseSegment) {
        return 20;
    }

    @Override
    public void save(Cargo cargo) {
        CargoDO cargoDO = CargoConverter.serialize(cargo);
        /**
         * 查询数据库中对应的货物对象
         * 存在更新，不存在新增
         */
        CargoDO oCargo = cargoMapper.selectById(cargoDO.getId());
        if (oCargo == null) {
            cargoMapper.insert(cargoDO);
        } else {
            cargoMapper.updateById(cargoDO);
        }
    }

    @Override
    public void remove(String id) {
        cargoMapper.deleteById(id);
    }
}
